<?php
App::uses ( 'Component', 'Controller' );
class Hungdv7GuessGameComponent extends Component {
	public function play($price, $guess1, $guess2, $guess3, $guess4) {
		$guesses = array (
				$guess1,
				$guess2,
				$guess3,
				$guess4 
		);
		$lessOrEqual = array ();
		$greater = array ();
		
		// check if guesses valid
		foreach ( $guesses as $guess ) {
			// check numeric number
			if (! is_numeric ( $guess )) {
				return json_encode ( array (
						'errorCode' => "2",
						'Message' => 'Not a number',
						'result' => "" 
				) );
			}
			
			// check negative number
			if ($guess < 0) {
				return json_encode ( array (
						'errorCode' => "3",
						'Message' => 'Negative number',
						'result' => "" 
				) );
			}
		}
		
		for($i = 0; $i < count ( $guesses ); $i ++) {
			if ($guesses [$i] <= $price) {
				// check duplicated in array $lessOrEquall
				if (in_array ( $guesses [$i], $lessOrEqual )) {
					return json_encode ( array (
							'errorCode' => "1",
							'Message' => 'duplicated',
							'result' => "" 
					) );
				}
				array_push ( $lessOrEqual, $guesses [$i] );
			} else {
				// check duplicated in array $greater
				if (in_array ( $guesses [$i], $greater )) {
					return json_encode ( array (
							'errorCode' => "1",
							'Message' => 'duplicated',
							'result' => "" 
					) );
				}
				array_push ( $greater, $guesses [$i] );
			}
		}
		
		$result1 = Set::sort ( $lessOrEqual, '{n}', 'desc' );
		$result2 = Set::sort ( $greater, '{n}', 'asc' );
		
		return json_encode ( array (
				'errorCode' => "0",
				'Message' => 'Success',
				'result' => array_merge ( $result1, $result2 ) 
		) );
	}
}